<template>
  <div class="product-card modern-card hover-lift" @click="navigateToDetail">
    <div class="product-image">
      <img :src="product.mainImage" :alt="product.name" class="product-img">

      <!-- 商品标签 -->
      <div class="product-tags">
        <span class="tag new-tag" v-if="showNew">✨ 新品</span>
        <span class="tag hot-tag" v-if="showHot">🔥 热销</span>
        <span v-if="product.discount > 0" class="tag discount-tag">
          -{{ Math.round(product.discount * 100) }}%
        </span>
      </div>

      <!-- 管理员删除按钮 -->
      <div class="product-admin-actions" v-if="isAdmin && product.status !== 0">
        <el-button type="danger" size="small" circle @click.stop="handleDelete" class="delete-btn">
          <el-icon>
            <Delete />
          </el-icon>
        </el-button>
      </div>

      <!-- 悬浮操作层 -->
      <div class="product-overlay">
        <div class="overlay-actions">
          <el-button circle size="small" @click.stop="toggleFavorite" class="overlay-btn favorite-btn">
            <el-icon>
              <Star v-if="!isFavorite" />
              <StarFilled v-else />
            </el-icon>
          </el-button>
          <el-button circle size="small" @click.stop="addToCart" class="overlay-btn cart-btn">
            <el-icon>
              <ShoppingCart />
            </el-icon>
          </el-button>
        </div>
      </div>
    </div>
    <div class="product-info">
      <h3 class="product-name">{{ product.name }}</h3>
      <div class="product-price">
        <span class="current-price">¥{{ product.price }}</span>
        <span class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</span>
      </div>
      <div class="product-meta">
        <span class="product-sales">已售 {{ product.sales || 0 }}件</span>
        <div class="product-rating" v-if="product.rating">
          <el-rate v-model="product.rating" disabled size="small" />
          <span class="rating-text">({{ product.reviewCount || 0 }})</span>
        </div>
      </div>
    </div>
    <div class="product-actions">
      <el-button type="primary" size="small" @click.stop="addToCart" class="btn-gradient">
        <el-icon><ShoppingCart /></el-icon>
        加入购物车
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Star, StarFilled, Delete, ShoppingCart } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const props = defineProps({
  product: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['product-deleted'])

const router = useRouter()
const isFavorite = ref(false)

// 判断是否为管理员
const isAdmin = computed(() => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  return userInfo.role === 'admin'
})

// 计算属性，处理后端返回的数字类型的isHot和isNew字段
const showHot = computed(() => {
  return props.product.isHot === 1 || props.product.isHot === true;
});

const showNew = computed(() => {
  return props.product.isNew === 1 || props.product.isNew === true;
});

// 删除商品
const handleDelete = () => {
  ElMessageBox.confirm(`确定要删除商品"${props.product.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request.delete(`/products/${props.product.id}`)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        // 通知父组件刷新商品列表
        emit('product-deleted')
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除商品失败:', error)
      if (error.response && error.response.data && error.response.data.message &&
        error.response.data.message.includes('foreign key constraint')) {
        ElMessage.error('该商品已被订单引用，无法删除')
      } else {
        ElMessage.error('删除商品失败')
      }
    }
  }).catch(() => {
    // 取消删除
  })
}

// 跳转到商品详情页
const navigateToDetail = () => {
  router.push({
    path: `/home/product/${props.product.id}`
  })
}

// 添加到购物车
const addToCart = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')

    if (!userInfo.id) {
      // 如果未登录，使用localStorage
      const cartItems = JSON.parse(localStorage.getItem('cartItems') || '[]')
      const existingItem = cartItems.find(item => item.id === props.product.id)

      if (existingItem) {
        existingItem.quantity += 1
      } else {
        cartItems.push({
          id: props.product.id,
          name: props.product.name,
          price: props.product.price,
          mainImage: props.product.mainImage,
          quantity: 1
        })
      }

      localStorage.setItem('cartItems', JSON.stringify(cartItems))
      window.emitter?.emit('cart-updated')
      ElMessage.success('已添加到购物车')
      return
    }

    // 如果已登录，调用后端API
    const cartData = {
      userId: userInfo.id,
      productId: props.product.id,
      quantity: 1
    }

    await request.post('/cart', cartData)
    window.emitter?.emit('cart-updated')
    ElMessage.success('已添加到购物车')
  } catch (error) {
    console.error('添加到购物车失败:', error)
    ElMessage.error('添加到购物车失败')
  }
}

// 切换收藏状态
const toggleFavorite = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.id) {
      ElMessage.warning('请先登录')
      return
    }

    // 使用toggle接口，更简单可靠
    const res = await request.post('/favorites/toggle', {
      userId: userInfo.id,
      productId: props.product.id
    })

    if (res.code === 200) {
      isFavorite.value = res.data // 后端返回新的收藏状态
      if (isFavorite.value) {
        ElMessage.success('已添加到收藏夹')
      } else {
        ElMessage.info('已从收藏夹移除')
      }
    } else {
      ElMessage.error(res.message || '收藏操作失败')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('收藏操作失败')
  }
}

// 检查收藏状态
const checkFavoriteStatus = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.id || !props.product) {
      return
    }

    const res = await request.get('/favorites/check', {
      params: {
        userId: userInfo.id,
        productId: props.product.id
      }
    })
    if (res.code === 200) {
      isFavorite.value = res.data
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error)
  }
}

// 组件挂载时检查收藏状态
onMounted(() => {
  checkFavoriteStatus()
})
</script>

<style scoped>
.product-card {
  background: var(--bg-primary);
  border-radius: var(--radius-xl);
  overflow: hidden;
  box-shadow: var(--shadow-md);
  transition: all var(--transition-normal);
  cursor: pointer;
  border: 1px solid var(--border-light);
  position: relative;
}

.product-card:hover {
  transform: translateY(-8px);
  box-shadow: var(--shadow-2xl);
}

.product-card:hover .product-overlay {
  opacity: 1;
  visibility: visible;
}

.product-image {
  position: relative;
  height: 240px;
  overflow: hidden;
  background: var(--gray-50);
}

.product-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform var(--transition-slow);
}

.product-card:hover .product-img {
  transform: scale(1.05);
}

.product-tags {
  position: absolute;
  top: var(--spacing-md);
  left: var(--spacing-md);
  z-index: 3;
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.tag {
  display: inline-flex;
  align-items: center;
  padding: 4px 8px;
  border-radius: var(--radius-full);
  font-size: var(--text-xs);
  font-weight: 600;
  color: white;
  backdrop-filter: blur(10px);
  box-shadow: var(--shadow-sm);
}

.new-tag {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
}

.hot-tag {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
}

.discount-tag {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
}

/* 悬浮操作层 */
.product-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  visibility: hidden;
  transition: all var(--transition-normal);
  z-index: 2;
}

.overlay-actions {
  display: flex;
  gap: var(--spacing-md);
}

.overlay-btn {
  width: 48px;
  height: 48px;
  border-radius: var(--radius-full);
  background: var(--bg-primary);
  border: none;
  box-shadow: var(--shadow-lg);
  transition: all var(--transition-fast);
}

.overlay-btn:hover {
  transform: scale(1.1);
  box-shadow: var(--shadow-xl);
}

.favorite-btn:hover {
  background: var(--warning-color);
  color: white;
}

.cart-btn:hover {
  background: var(--primary-color);
  color: white;
}

.product-info {
  padding: var(--spacing-lg);
  background: var(--bg-primary);
}

.product-name {
  margin: 0 0 var(--spacing-md);
  font-size: var(--text-lg);
  font-weight: 600;
  color: var(--text-primary);
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  min-height: 2.8em;
}

.product-price {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-sm);
}

.current-price {
  font-size: var(--text-xl);
  font-weight: 700;
  color: var(--error-color);
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.original-price {
  font-size: var(--text-sm);
  color: var(--text-tertiary);
  text-decoration: line-through;
}

.product-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--spacing-md);
}

.product-sales {
  font-size: var(--text-sm);
  color: var(--text-secondary);
}

.product-rating {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.rating-text {
  font-size: var(--text-xs);
  color: var(--text-tertiary);
}

.product-actions {
  padding: 0 var(--spacing-lg) var(--spacing-lg);
}

.product-actions .btn-gradient {
  width: 100%;
  height: 40px;
  border-radius: var(--radius-lg);
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-xs);
}

.product-admin-actions {
  position: absolute;
  top: var(--spacing-md);
  right: var(--spacing-md);
  z-index: 4;
}

.delete-btn {
  background: rgba(239, 68, 68, 0.9);
  border: none;
  backdrop-filter: blur(10px);
  box-shadow: var(--shadow-md);
}

.delete-btn:hover {
  background: var(--error-color);
  transform: scale(1.1);
}

.product-admin-actions .el-button {
  opacity: 0.8;
  transition: opacity 0.3s;
}

.product-admin-actions .el-button:hover {
  opacity: 1;
}

/* 夜间模式样式 */
html.dark .product-card {
  background: #2a2a2a !important;
  border-color: #404040 !important;
  color: var(--el-text-color-primary);
}

html.dark .product-info {
  color: var(--el-text-color-primary);
}

html.dark .product-name {
  color: var(--el-text-color-primary) !important;
}

html.dark .product-meta {
  color: var(--el-text-color-secondary);
}

html.dark .product-sales {
  color: var(--el-text-color-secondary);
}

html.dark .rating-text {
  color: var(--el-text-color-secondary);
}

html.dark .product-image {
  background: #3a3a3a;
}
</style>